﻿using System;
using System.Diagnostics;
using System.Windows.Input;

namespace Com.CodePlex.SPC3.SPbAM.Controller {

	//http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030 
	public class RelayCommand : ICommand {

		readonly Action<object> _execute;
		readonly Predicate<object> _canExecute;

		public RelayCommand(Action<object> execute)
			: this(execute, null) {
		}

		public RelayCommand(Action<object> execute, Predicate<object> canExecute) {
			if (execute == null) {
				throw new ArgumentNullException("execute");
			}
			_execute = execute;
			_canExecute = canExecute;
		}

		[DebuggerStepThrough]
		public bool CanExecute(object parameter) {
			return _canExecute == null ? true : _canExecute(parameter);
		}

		//http://stackoverflow.com/questions/2281566/is-josh-smiths-implementation-of-the-relaycommand-flawed
		public event EventHandler CanExecuteChanged {
			//http://stackoverflow.com/questions/2763630/how-does-commandmanager-requerysuggested-work
			add { CommandManager.RequerySuggested += value; }
			remove { CommandManager.RequerySuggested -= value; }
		}

		public void Execute(object parameter) {
			_execute(parameter);
		}
	}
}